<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>pytho万能分布式函数调度框架</title>
    <link href="{{ url_for('static',filename='css_cdn/twitter-bootstrap/3.3.7/css/bootstrap.min.css') }}" rel="stylesheet">
    <link href="{{ url_for('static',filename='css_cdn/font-awesome/4.7.0/css/font-awesome.min.css') }}" rel="stylesheet">
    <link rel="stylesheet"
        href="{{ url_for('static',filename='css_cdn/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static',filename='assets/css/jquery.mCustomScrollbar.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static',filename='assets/css/custom.css') }}">
    <!-- 在其他 link 标签后添加 -->
    <link href="{{ url_for('static',filename='css_cdn/select2/4.0.13/css/select2.min.css') }}" rel="stylesheet">
    <link href="{{ url_for('static',filename='css/content_page_style.css') }}" rel="stylesheet">


    <script src="{{ url_for('static',filename='js/jquery-1.11.0.min.js') }}" type="text/javascript"></script>
    <!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.11.0/jquery.min.js"></script> -->
    <!-- 在其他 script 标签后添加 -->
    <!-- <script src="https://cdn.bootcdn.net/ajax/libs/select2/4.0.13/js/select2.min.js"></script> -->
    <script src="{{ url_for('static',filename='/js/select2.min.js') }}"></script>
    <script src="{{ url_for('static',filename='js_cdn/bootstrap/3.3.7/js/bootstrap.min.js') }}"></script>


    <script src="{{ url_for('static',filename='js/moment-with-locales.min.js') }}"></script>
    <script src="{{ url_for('static',filename='js/bootstrap-datetimepicker.min.js') }}"></script>
    <!-- <script src="https://cdn.bootcss.com/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script> -->
    <!-- <script type="text/javascript" src="https://cdn.bootcss.com/echarts/3.3.0/echarts.js"></script> -->
    <script type="text/javascript" src="{{ url_for('static',filename='js/echarts.min.js') }}"></script>

    <script src="{{ url_for('static',filename='assets/js/jquery.mCustomScrollbar.concat.min.js') }}"></script>
    <script src="{{ url_for('static',filename='assets/js/custom.js') }}"></script>
    <style>

    </style>
</head>

<body>





    <!-- <li><a href="{{url_for('logout')}}">退出</a></li> -->

    <!-- 添加固定导航栏
    <nav class="navbar navbar-default navbar-fixed-top" style="min-height: 40px;">
        <div class="container-fluid">
            <div class="navbar-header pull-right">
                <a href="{{url_for('logout')}}" class="btn btn-danger" style="margin: 4px 15px;">
                    <i class="fa fa-sign-out"></i> 退出
                </a>
            </div>
        </div>
    </nav> -->

    <!-- 删除原来的退出按钮 -->
    <!-- 调整主容器的上边距 -->
    <div class="container-fluid" style="margin-top: 5px;">
        <div style="margin-top: 5px;">
            <!-- {# <h1 style="text-align:center;">Pro sidebar template</h1>#} -->


            <form class="form-inline" role="form" style="float: left">
                <div class="form-group ">
                    <label for="col_name_search">队列名称：</label>
                    <select class="form-control" id="col_name_search">
                        <option value="">请选择队列...</option>
                    </select>
                </div>
                <div class="form-group marginLeft20">
                    <label for="start_time">起始时间：</label>
                    <input type="text" class="form-control" id="start_time">
                </div>
                <div class="form-group marginLeft20">
                    <label for="end_time">截止时间：</label>
                    <input type="text" class="form-control" id="end_time">
                </div>
                <label for="sucess_status" class="marginLeft20">函数运行状态：</label>
                <select class="form-control" id="sucess_status">
                    <option value="1">全部</option>
                    <option value="2">成功</option>
                    <option value="3">失败</option>

                </select>
                <div class="form-group marginLeft20">
                    <label for="params">函数参数：</label>
                    <input type="text" class="form-control" id="params" placeholder="请输入参数。。">
                </div>
                <button type="button" class="btn btn-default marginLeft20"
                    onclick="document.getElementById('table').style.display = 'block';$('#echartsArea').css('display','none');startRun();queryResult(currentColName,0,true)">查询</button>
            </form>

            <!-- <button id="statistic" type="button" class="btn btn-info btn-sm marginLeft20" onclick="statistic()">生成统计表</button> -->

            <button id="autoFresh" type="button" class="btn btn-success btn-sm marginLeft20" style="float2: right"
                onclick="startOrStop()">自动刷新中</button>
            <!-- <p id="echartsInfoTex" style="clear: both;margin-top: 30px;background-color:yellowgreen ;width:600px;color: white;text-shadow: 0 0 10px black;font-size: 16px;display: none"></p>
            <p id="Last1minInfoTex" style="clear: both;margin-top: 10px;background-color:#00ccff;width:600px;color: white;text-shadow: 0 0 10px black;font-size: 16px;"></p>
            <p id="resultInfoTex" style="clear: both;margin-top: 10px;background-color:green;width:600px;color: white;text-shadow: 0 0 10px black;font-size: 16px;"></p>
             -->
            <p id="echartsInfoTex"
                style="clear: both;margin-top: 30px;background-color:yellowgreen ;width:600px;color: white;text-shadow: 0 0 10px black;font-size: 16px;display: none">
            </p>
            <div style="display: flex; gap: 20px; margin-top: 10px;">
                <p id="resultInfoTex"
                    style="margin: 0; background-color:green;width:600px;color: white;text-shadow: 0 0 10px black;font-size: 16px;">
                </p>
                <p id="Last1minInfoTex"
                    style="margin: 0; background-color:#00ccff;width:600px;color: white;text-shadow: 0 0 10px black;font-size: 16px;">
                </p>
            </div>


            <div class="table-responsive" style="margin-top: 10px;">
                <table id="table" class="table table-striped">

                </table>
            </div>
        </div>
    </div>





    <script>

        // 在现有的变量声明后添加
        var allQueues = [];  // 存储所有队列数据
        var currentColName;
        var runStatus = 1;

        $(document).ready(function () {
            // ... 现有的代码 ...

            // 初始化日期时间选择器
            $('#start_time, #end_time').datetimepicker({
                format: 'YYYY-MM-DD HH:mm:ss',
                locale: 'zh-cn',
                sideBySide: true,  // 日期和时间选择器并排显示
                showClear: true,   // 显示清除按钮
                showClose: true,   // 显示关闭按钮
                showTodayButton: true,  // 显示今天按钮
                icons: {
                    time: 'fa fa-clock-o',
                    date: 'fa fa-calendar',
                    up: 'fa fa-chevron-up',
                    down: 'fa fa-chevron-down',
                    previous: 'fa fa-chevron-left',
                    next: 'fa fa-chevron-right',
                    today: 'fa fa-crosshairs',
                    clear: 'fa fa-trash',
                    close: 'fa fa-times'
                }
            });

            // ... 现有的代码 ...
        });

        // 页面加载完成后立即获取所有队列
        $(document).ready(function () {
            $.ajax({
                url: "{{ url_for('query_cols_view')}}",
                data: { col_name_search: '' },
                async: true,
                success: function (result) {
                    allQueues = result;
                    var html = '<option value="">请选择队列...</option>';
                    for (var item of result) {
                        html += '<option value="' + item.collection_name + '">' +
                            item.collection_name + '&nbsp;&nbsp;&nbsp;&nbsp;(result_count:' + item.count + ')</option>';
                    }
                    $("#col_name_search").html(html);

                    // 初始化选择框的搜索功能
                    $("#col_name_search").select2({
                        placeholder: "请输入队列名称搜索...",
                        allowClear: true,
                        width: '300px'
                    });

                    // 监听选择变化
                    $("#col_name_search").on('change', function () {
                        var selectedQueue = $(this).val();
                        console.log("Selected queue:", selectedQueue);
                        currentColName = selectedQueue;
                        // if(selectedQueue) {
                        //     queryResult(selectedQueue, 0, true);
                        // }
                    });
                }
            });
        });


        String.prototype.format = function () {
            var values = arguments;
            return this.replace(/\{(\d+)\}/g, function (match, index) {
                if (values.length > index) {
                    return values[index];
                } else {
                    return "";
                }
            });
        };

        function dateToString(date) {
            const year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let hour = date.getHours();
            let minute = date.getMinutes();
            let second = date.getSeconds();
            month = month > 9 ? month : ('0' + month);
            day = day > 9 ? day : ('0' + day);
            hour = hour > 9 ? hour : ('0' + hour);
            minute = minute > 9 ? minute : ('0' + minute);
            second = second > 9 ? second : ('0' + second);
            return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
        }


        //昨天的时间
        var day1 = new Date();
        day1.setDate(day1.getDate() - 2);

        //明天的时间
        var day2 = new Date();
        day2.setDate(day2.getDate() + 1);

        $("#start_time").val(dateToString(day1));
        $("#end_time").val(dateToString(day2));
        useAsync = false;


        //searchCols();
        useAsync = true;

        function queryResult(col_name, page, manualOperate) {
            if (currentColName === undefined) {
                return;
            }

            $('#echartsArea').css('display', 'none');
            // currentColName = col_name;
            if (manualOperate === true) {
                document.getElementById('table').style.display = 'block';
                updateTopText();
                updateQueryText();
            }

            if (runStatus === 0) {
                return;
            }


            $.ajax({
                url: "{{ url_for('query_result_view')}}", data: {
                    col_name: col_name, start_time: $("#start_time").val(),
                    end_time: $("#end_time").val(), is_success: $("#sucess_status").val(), function_params: $("#params").val(), page: page
                }, async: useAsync, success: function (result, status) {
                    // console.info(result);

                    var html = '  <thead>\n' +
                        '                    <tr>\n' +
                        '                        <th>执行机器-进程-脚本</th>\n' +

                        '                        <th>函数名称</th>\n' +
                        '                        <th>函数入参</th>\n' +
                        '                        <th>函数结果</th>\n' +
                        '                        <th>消息发布时间</th>\n' +
                        '                        <th>开始执行时间</th>\n' +
                        '                        <th>消耗时间(秒)</th>\n' +
                        '                        <th>执行次数(重试)</th>\n' +
                        '                        <th>运行状态</th>\n' +
                        '                        <th>是否成功</th>\n' +
                        '                        <th>错误原因</th>\n' +


                        '                        <th>线程(协程)数</th>\n' +
                        '                    </tr>\n' +
                        '                    </thead>' +
                        '<tbody>';
                    for (var item of result) {
                        // console.info(item);
                        var displayLevel = "success";
                        if (item.run_times > 1) {
                            displayLevel = "warning";
                        }

                        if (item.success === false) {
                            displayLevel = "danger";
                        }
                        var tr = ' <tr class="{0}">\n' +

                            '                        <td>{1}</td>\n' +
                            '                        <td>{2}</td>\n' +
                            '                        <td>{3}</td>\n' +
                            '                        <td>{4}</td>\n' +
                            '                        <td>{5}</td>\n' +
                            '                        <td>{6}</td>\n' +
                            '                        <td>{7}</td>\n' +
                            '                        <td>{8}</td>\n' +
                            '                        <td>{9}</td>\n' +
                            '                        <td>{10}</td>\n' +
                            '                        <td>{11}</td>\n' +
                            '                        <td>{12}</td>\n' +

                            '                    </tr>';
                        var successText = item.success === true ? "成功" : "失败";
                        <!--                    console.info(item.run_status);-->
                        var run_status_text = item.run_status;
                        if (item.run_status === "running") {
                            successText = "未完成";
                            displayLevel = "info";
                            if (Date.now() / 1000 - item.time_start > 600) {
                                run_status_text = "running?";
                            }
                        }

                        var time_start_obj = new Date(item.time_start * 1000);
                        var time_start_str = dateToString(time_start_obj);

                        tr = tr.format(displayLevel, item.host_process + ' - ' + item.script_name, item.function, item.params_str, item.result, item.publish_time_format,
                            time_start_str, item.time_cost, item.run_times, run_status_text, successText, item.exception, item.total_thread);
                        html += tr;
                    }
                    html += '</tbody>';
                    $("#table").html(html);

                    // document.getElementById('echartsArea').style.display = 'none';


                }
            });
            // if (manualOperate === true) {
            //     updateQueryText()
            // }
        }

        function updateQueryText() {
            if (currentColName === undefined) {
                return;
            }

            $.ajax({
                url: "{{ url_for('speed_stats')}}", data: {
                    col_name: currentColName, start_time: $("#start_time").val(),
                    end_time: $("#end_time").val()
                }, async: useAsync, success: function (result, status) {
                    var msg = ' {0} 队列,所选查询时间范围内运行成功了{1}次,失败了{2}次'.format(currentColName, result.success_num, result.fail_num);
                    console.info(msg);
                    $('#resultInfoTex').html(msg);
                }
            })
        }

        // queryResult(currentColName, 0, true);


        function updateTopText() {
            if (currentColName === undefined) {
                return;
            }
            var t1 = new Date(new Date().getTime() - 60000);
            var t2 = new Date();
            $.ajax({
                url: "{{ url_for('speed_stats')}}", data: {
                    col_name: currentColName, start_time: dateToString(t1), end_time: dateToString(t2)
                }, async: useAsync, success: function (result, status) {
                    var msg = ' {0} 队列,最近一分钟内运行成功了{1}次,失败了{2}次'.format(currentColName, result.success_num, result.fail_num);
                    console.info(msg);
                    $('#Last1minInfoTex').text(msg);
                }
            })
        }

        updateTopText();
        updateQueryText();
        setInterval(updateQueryText, 30000);
        setInterval(updateTopText, 30000);

        function autoFreshResult() {
            if (currentColName === undefined) {
                return;
            }
            queryResult(currentColName, 0, false);
        }

        // setInterval(autoFreshResult, 30000);

        iid = setInterval(autoFreshResult, 5000);
        

        function startRun() {
            $("#autoFresh").text("自动刷新中");
            $("#autoFresh").removeClass("btn-danger");
            $("#autoFresh").addClass("btn-success");
            iid = setInterval(autoFreshResult, 5000);
            runStatus = 1;
        }

        function stopRun() {
            $("#autoFresh").text("暂停刷新了");
            $("#autoFresh").removeClass("btn-success");
            $("#autoFresh").addClass("btn-danger");
            clearInterval(iid);
            runStatus = 0;
        }

        function startOrStop() {
            if (runStatus === 1) {
                stopRun();
            } else {
                startRun();
            }
        }

       

        

       


    </script>
</body>

</html>